import { Component, OnInit } from '@angular/core';
import { FadeInTop } from "../../shared/animations/fade-in-top.decorator";
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import { NotificationService } from "../../shared/utils/notification.service";
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var Viewer: any;
@FadeInTop()
@Component({
	selector: 'sa-car-page',
	templateUrl: './car-page.component.html',
	styleUrls: ['./car-page.component.css']
})
export class CarPageComponent implements OnInit {
	validatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			companyId: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择所属公司'
					}
				}
			},
			deviceId: {
				validators: {
					notEmpty: {
						message: '请输入设备ID'
					},
					stringLength: {
						max: 50,
						message: '设备ID50字以内'
					},
					integer: {
						message: '请输入整数'
					},
					remote: {
						message: '设备ID已存在,请输入新的ID',
						url: config.BaseURL + "car/validateDeviceId.html",
						data: function (validator) {
							return {
								id: validator.getFieldElements('deviceId').attr("carId")
							};
						},
					}
				}
			},
			carNumber: {
				validators: {
					notEmpty: {
						message: '请输入车牌号码'
					}
				}
			},
			loadCapacity: {
				validators: {
					callback: {
						callback: function (value, validator, $field) {
							if (value) {
								var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
								if (!reg.test(value)) {
									return {
										valid: false,
										message: '请输入正数荷载重量'
									}
								} else {
									return true;
								}
							} else {
								return true;
							}
						}.bind(this)
					},
				}
			},
			carUseType: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择车辆用途'
					}
				}
			},
			userNameForCreate: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择安装人员'
					}
				}
			},
			sensorAmount: {
				validators: {
					integer: {
						message: '请输入整数'
					}
				}
			},
			carAxleAmount: {
				validators: {
					integer: {
						message: '请输入整数'
					}
				}
			},
			phone: {
				validators: {
					integer: {
						message: '请输入数字电话号码'
					}
				}
			},
			carAttribution: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择车辆归属'
					}
				}
			},
			motorcadeContactPhone: {
				validators: {
					integer: {
						message: '请输入数字电话号码'
					}
				}
			}
		}

	};
	isAdmin: boolean = false;
	companyList: any = [];
	page_title: string = '新增';
	pageType: string = 'new';
	carId = null;
	isDeviceId: boolean = false;  //后台验证,是否存在设备ID
	fileData: File = null;
	timer: any;
	page: any = {
		companyId: '',
		deviceId: '',
		carNumber: '',
		loadCapacity: '',
		unit: '1',
		useTypeL1: '',
		useTypeL2: '',
		gpsId: '',
		isShared: '0',
		type: '1', //设备类型
		sensorType: '2',
		sensorAmount: '',
		sensorChannel: [],
		hwVersion: '',
		sim: '',
		carAxleAmount: '',
		carType: '',
		gpsAntenna: '',
		gsmAntenna: '',
		phone: '',
		remark: '',
		driverName: '',
		inputDate: '',
		sensorAxle: [], //传感器通道
		sensorPosition: [], //安装位置
		imageInfo: [], //图片列表
		carAttribution: '', //车辆归属
		motorcadeContact: '', //车队联系人
		motorcadeContactPhone: '', //车队联系电话
		motorcadeName: '', //车队名称
		userNameForCreate: '', //责任人名称
		userIdForCreate: '' //责任人ID
	};
	unitList = [{
		label: '吨',
		value: '1'
	}, {
		label: '千克',
		value: '2'
	}];
	hwVersionList: any = [{
		label: 'v4',
		value: 'v4'
	}, {
		label: 'v7',
		value: 'v7'
	}];
	selectedCompanyName = '';//选中公司名称
	selectedCompanyId = '';//选中公司的ID
	curPage = 0;//缓存页码
	imgFileTitle = '点击更换';
	fileList: File = null;
	fileImg = '';
	carTypeList = carTypeListObj.carTypeList
	sensorArr: any = [{
		id: 1,
		text: '通道1',
		checked: false
	}, {
		id: 2,
		text: '通道2',
		checked: false
	}, {
		id: 3,
		text: '通道3',
		checked: false
	}, {
		id: 4,
		text: '通道4',
		checked: false
	}, {
		id: 5,
		text: '通道5',
		checked: false
	}, {
		id: 6,
		text: '通道6',
		checked: false
	}, {
		id: 7,
		text: '通道7',
		checked: false
	}, {
		id: 8,
		text: '通道8',
		checked: false
	}, {
		id: 9,
		text: '通道9',
		checked: false
	}, {
		id: 10,
		text: '通道10',
		checked: false
	}, {
		id: 11,
		text: '通道11',
		checked: false
	}, {
		id: 12,
		text: '通道12',
		checked: false
	}, {
		id: 13,
		text: '通道13',
		checked: false
	}, {
		id: 14,
		text: '通道14',
		checked: false
	}, {
		id: 15,
		text: '通道15',
		checked: false
	}, {
		id: 16,
		text: '通道16',
		checked: false
	}]
	sensorAxleFront: any = [] //通道前
	sensorAxleAfter: any = [] //通道后
	installArray: any = [] //安装位置
	checkChannel: any = []//选中通道数组
	ChannelLen: any = ''//原始轴的个数

	// gps选项
	gpsOptions: any = allSelectOptionsObj.gpsOptions;
	// gsm选项
	gsmOptions: any = allSelectOptionsObj.gsmOptions;

	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService, private notificationService: NotificationService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.carId = queryParams.id;
			this.pageType = queryParams.type;
			this.curPage = queryParams.nowPage;
		});
	}
	sensorChange(id, e) {
		var sensorAxleList = [];
		this.page.sensorChannel = [];
		let sensor;
		var listFront = JSON.parse(JSON.stringify(this.sensorAxleFront));
		var listAfter = JSON.parse(JSON.stringify(this.sensorAxleAfter));
		var listChannel = JSON.parse(JSON.stringify(this.checkChannel));
		var that = this;

		if (e.target.checked) {
			that.sensorArr[id - 1].checked = true;
			sensor = {
				mark: id,
				text: id,
				checked: false,
				isDisable: false
			}
			listFront.push(sensor);
			listAfter.push(sensor);
			listChannel.push(sensor);
			that.sensorAxleFront = that.deepClone(listFront);
			that.sensorAxleAfter = that.deepClone(listAfter);
			that.checkChannel = that.deepClone(listChannel);
			// that.sensorAxleAfter = that.deepClone(that.sensorAxleFront);
			// that.checkChannel = that.deepClone(that.sensorAxleFront);

			that.sensorAxleFront.sort(that.compare('mark'));
			that.sensorAxleAfter.sort(that.compare('mark'));
			that.checkChannel.sort(that.compare('mark'));
		} else {
			that.sensorArr[id - 1].checked = false;
			if (that.sensorAxleFront.length != 0) {
				for (let i = 0; i < that.sensorAxleFront.length; i++) {
					if (that.sensorAxleFront[i].mark == id) {
						listFront.splice(i, 1);
						listAfter.splice(i, 1);
						listChannel.splice(i, 1);
						this.clear(id)
						that.sensorAxleFront = that.deepClone(listFront);
						that.sensorAxleAfter = that.deepClone(listAfter);
						that.checkChannel = that.deepClone(listChannel);

						// that.sensorAxleAfter = that.deepClone(that.sensorAxleFront);
						// that.checkChannel = that.deepClone(that.sensorAxleFront);

					}
				}
			}
		}
		for (let item of this.sensorArr) {
			if (item.checked) {
				this.page.sensorChannel.push(item.id);
			}
		}
		this.page.sensorAmount = this.page.sensorChannel.length || '';

		for (let j = 0; j < this.sensorAxleAfter.length; j++) {
			if (!this.sensorAxleAfter[j].checked && !this.sensorAxleAfter[j].isDisable) {
				sensorAxleList.push(0)
			} else if (this.sensorAxleAfter[j].checked) {
				sensorAxleList.push(2)
			} else if (this.sensorAxleAfter[j].isDisable) {
				sensorAxleList.push(1)
			}
		}
		this.page.sensorAxle = this.deepClone(sensorAxleList);

		this.showCheck(that.checkChannel)
	}
	showCheck(value) {
		var showCheckList = [];
		for (var a = 0; a < this.installArray.length; a++) {
			for (var b = 0; b < this.installArray[a].positionLMR.length; b++) {
				for (var c = 0; c < this.installArray[a].positionLMR[b].sensorChannel.length; c++) {
					showCheckList.push(this.installArray[a].positionLMR[b].sensorChannel[c])
				}
			}
		}

		for (var i = 0; i < value.length; i++) {
			for (var j = 0; j < showCheckList.length; j++) {
				if (value[i].mark == showCheckList[j]) {
					value[i].isDisable = true;
					break;
				}
			}
		}

		this.checkChannel = this.deepClone(value);
	}
	clear(value) {
		for (let j = 0; j < this.installArray.length; j++) {
			var sensorChannelL = this.installArray[j].positionLMR[0].sensorChannel;
			var sensorChannelM = this.installArray[j].positionLMR[1].sensorChannel;
			var sensorChannelR = this.installArray[j].positionLMR[2].sensorChannel;
			for (var k = 0; k < sensorChannelL.length; k++) {
				if (sensorChannelL[k] == value) {
					sensorChannelL.splice(k, 1);
				}
				this.installArray[j].positionLMR[0].sensorChannel = this.deepClone(sensorChannelL);
				this.installArray[j].positionLMR[0].sensorChannel.sort(this.sortNumber);
			}
			for (var h = 0; h < sensorChannelM.length; h++) {
				if (sensorChannelM[h] == value) {
					sensorChannelM.splice(h, 1);
				}
				this.installArray[j].positionLMR[1].sensorChannel = this.deepClone(sensorChannelM)
				this.installArray[j].positionLMR[1].sensorChannel.sort(this.sortNumber);;
			}
			for (var f = 0; f < sensorChannelR.length; f++) {
				if (sensorChannelR[f] == value) {
					sensorChannelR.splice(f, 1);
				}
				this.installArray[j].positionLMR[2].sensorChannel = this.deepClone(sensorChannelR);
				this.installArray[j].positionLMR[2].sensorChannel.sort(this.sortNumber);
			}
		}

		this.page.sensorPosition = this.deepClone(this.installArray)
	}
	compare(property) {
		return function (a, b) {
			var value1 = a[property];
			var value2 = b[property];
			return value1 - value2;
		}
	}
	//通道 前
	sensorAxleFrontChange(item, e) {
		let sensorAxleList = [];
		for (let i = 0; i < this.sensorAxleFront.length; i++) {
			if (item.mark == this.sensorAxleFront[i].mark) {
				if (e.target.className.indexOf('wayCheck') != -1) {

					this.sensorAxleFront[i].checked = false;
					this.sensorAxleAfter[i].isDisable = false
				} else {
					this.sensorAxleFront[i].checked = true;
					this.sensorAxleAfter[i].isDisable = true
				}
			}
		}

		for (let j = 0; j < this.sensorAxleAfter.length; j++) {
			if (!this.sensorAxleAfter[j].checked && !this.sensorAxleAfter[j].isDisable) {
				sensorAxleList.push(0)
			} else if (this.sensorAxleAfter[j].checked) {
				sensorAxleList.push(2)
			} else if (this.sensorAxleAfter[j].isDisable) {
				sensorAxleList.push(1)
			}
		}
		this.page.sensorAxle = this.deepClone(sensorAxleList);
	}
	//深拷贝浅拷贝
	deepClone(obj) {
		let objClone = Array.isArray(obj) ? [] : {};
		if (obj && typeof obj === "object") {
			for (let key in obj) {
				if (obj.hasOwnProperty(key)) {
					//判断ojb子元素是否为对象，如果是，递归复制
					if (obj[key] && typeof obj[key] === "object") {
						objClone[key] = this.deepClone(obj[key]);
					} else {
						//如果不是，简单复制
						objClone[key] = obj[key];
					}
				}
			}
		}
		return objClone;
	}
	//通道 后
	sensorAxleAfterChange(item, e) {
		let sensorAxleList = [];
		for (let i = 0; i < this.sensorAxleAfter.length; i++) {
			if (item.mark == this.sensorAxleAfter[i].mark) {
				if (e.target.className.indexOf('wayCheck') != -1) {

					this.sensorAxleAfter[i].checked = false;
					this.sensorAxleFront[i].isDisable = false
				} else {
					this.sensorAxleAfter[i].checked = true;
					this.sensorAxleFront[i].isDisable = true
				}
			}
		}

		for (let j = 0; j < this.sensorAxleFront.length; j++) {
			if (!this.sensorAxleFront[j].checked && !this.sensorAxleFront[j].isDisable) {
				sensorAxleList.push(0)
			} else if (this.sensorAxleFront[j].checked) {
				sensorAxleList.push(1)
			} else if (this.sensorAxleFront[j].isDisable) {
				sensorAxleList.push(2)
			}
		}
		this.page.sensorAxle = this.deepClone(sensorAxleList)
	}
	//车轴数量出现安装位置
	carAxleAmountChange(value) {
		var array = [];
		if (isNaN(value) == true) {
			this.jsonApiService.message('请输入数字');
			$('#carAxleAmount').val('');
			this.page.carAxleAmount = "";
			return;
		} else if (value > 6) {
			this.jsonApiService.message('车轴数量不能大于6');
			$('#carAxleAmount').val('');
			this.page.carAxleAmount = "";
			return;
		} else {
			if (value == "0") {
				this.jsonApiService.message('车轴数量不能为0');
				$('#carAxleAmount').val('');
				this.page.carAxleAmount = "";
				return;
			} else if (value == "") {
				if (this.ChannelLen == 0 && this.page.carAxleAmount == "") {
					this.showLocation(this.page.sensorChannel, this.page.sensorPosition, value)
					// this.installArray = this.page.sensorPosition
				} else {
					for (var i = 0; i < 6; i++) {
						var positionLMR = {
							"index": i + 1,
							"positionLMR": [
								{
									"position": "L",
									"sensorChannel": []
								},
								{
									"position": "M",
									"sensorChannel": []
								},
								{
									"position": "R",
									"sensorChannel": []
								}
							]
						}
						array.push(positionLMR);
					}
					this.installArray = this.deepClone(array);
					this.clearcheckChannel()
				}
			} else if (value == this.ChannelLen) {
				this.showLocation(this.page.sensorChannel, this.page.sensorPosition, value)
				// this.showLocation(this.page.sensorChannel,this.installArray)
			} else {
				for (var i = 0; i < value; i++) {
					var positionLMR = {
						"index": i + 1,
						"positionLMR": [
							{
								"position": "L",
								"sensorChannel": []
							},
							{
								"position": "M",
								"sensorChannel": []
							},
							{
								"position": "R",
								"sensorChannel": []
							}
						]
					}
					array.push(positionLMR);
				}
				this.installArray = this.deepClone(array);
				this.clearcheckChannel()
			}
		}

		// for(let i=0;i<this.checkChannel.length;i++){
		// 	this.checkChannel[i].isDisable = false;
		// }
	}
	//清除安装位置轴数选中
	clearcheckChannel() {
		for (var a = 0; a < this.checkChannel.length; a++) {
			this.checkChannel[a].isDisable = false;
		}
	}
	axisType: any = '' //打开那个方向传感器轴
	axisIndex: any = '' //打开那个传感器轴
	//添加传感器通道
	addinstall(index, type, modal) {
		this.axisType = type;
		this.axisIndex = index;
		if (this.page.sensorAmount) {
			modal.show();
		} else {
			this.jsonApiService.message('请先选择传感器');
		}

	}
	//选择弹框中的传感器通道
	choiceChannel(item, e) {
		for (let i = 0; i < this.checkChannel.length; i++) {
			if (item.mark == this.checkChannel[i].mark) {
				if (e.target.className.indexOf('check') != -1) {
					this.checkChannel[i].checked = false;
				} else {
					this.checkChannel[i].checked = true;
				}
			}
		}
	}
	//取消传感器弹框
	lgModalhide(modal) {
		this.axisType = '';
		this.axisIndex = '';
		modal.hide();
		for (let i = 0; i < this.checkChannel.length; i++) {
			if (this.checkChannel[i].checked) {
				this.checkChannel[i].checked = false;
			}
		}
		// this.checkChannel = [];
	}
	//确定传感器
	lgModalConfirm(modal) {
		let newChannel = []
		for (let i = 0; i < this.checkChannel.length; i++) {
			if (this.checkChannel[i].checked) {
				this.checkChannel[i].isDisable = true;
				if (this.axisType == 'left') {
					this.installArray[this.axisIndex - 1].positionLMR[0].sensorChannel.push(this.checkChannel[i].mark);
				} else if (this.axisType == 'middle') {
					this.installArray[this.axisIndex - 1].positionLMR[1].sensorChannel.push(this.checkChannel[i].mark);
				} else if (this.axisType == 'right') {
					this.installArray[this.axisIndex - 1].positionLMR[2].sensorChannel.push(this.checkChannel[i].mark);
				}
				// newChannel.push(this.checkChannel[i].mark)
			}
		}

		this.installArray[this.axisIndex - 1].positionLMR[0].sensorChannel.sort(this.sortNumber);
		this.installArray[this.axisIndex - 1].positionLMR[1].sensorChannel.sort(this.sortNumber);
		this.installArray[this.axisIndex - 1].positionLMR[2].sensorChannel.sort(this.sortNumber);
		this.lgModalhide(modal);
	}
	//排序
	sortNumber(a, b) {//升序
		return a - b
	}
	//删除选中的传感器
	cancelChannel(index, type, channel) {
		let valueList;
		if (type == 'left') {
			valueList = this.installArray[index - 1].positionLMR[0].sensorChannel;
			for (let i = 0; i < valueList.length; i++) {
				if (valueList[i] == channel) {
					valueList.splice(i, 1);
				}
			}
			this.installArray[index - 1].positionLMR[0].sensorChannel = this.deepClone(valueList)
		} else if (type == 'middle') {
			valueList = this.installArray[index - 1].positionLMR[1].sensorChannel;
			for (let j = 0; j < valueList.length; j++) {
				if (valueList[j] == channel) {
					valueList.splice(j, 1);
				}
			}
			this.installArray[index - 1].positionLMR[1].sensorChannel = this.deepClone(valueList)

		} else if (type == 'right') {
			valueList = this.installArray[index - 1].positionLMR[2].sensorChannel;
			for (let k = 0; k < valueList.length; k++) {
				if (valueList[k] == channel) {
					valueList.splice(k, 1);
				}
			}
			this.installArray[index - 1].positionLMR[2].sensorChannel = this.deepClone(valueList)
		}

		for (let l = 0; l < this.checkChannel.length; l++) {
			if (this.checkChannel[l].mark == channel) {
				this.checkChannel[l].isDisable = false;
			}
		}
	}
	//单位change回调
	unitChange(val) {
		this.page.unit = val;
	}
	//传感器类型change回调
	sensorTypeChange(val) {
		this.page.sensorType = val;
	}
	sensorSelected(data) {
		this.page.sensorType = data.sensorType;
		this.inputParam = data.inputParam
	}
	//硬件版本change回调
	hwVersionChange(val) {
		this.page.hwVersion = val;
	}
	//gps天线change回调
	gpsAntennaChange(val) {
		this.page.gpsAntenna = val;
		// if (this.page.gsmAntenna != val) {
		// 	this.gsmAntennaChange(val)
		// }
		for (var i = 0; i < allSelectOptionsObj.gsmOptions.length; i++) {
			if (allSelectOptionsObj.gsmOptions[i].text == val) {
				this.page.gsmAntenna = val;
			}
		}
	}
	//gsm天线change回调
	gsmAntennaChange(val) {
		this.page.gsmAntenna = val;
		// if (this.page.gpsAntenna != val) {
		// 	this.gpsAntennaChange(val)
		// }
		for (var i = 0; i < allSelectOptionsObj.gpsOptions.length; i++) {
			if (allSelectOptionsObj.gpsOptions[i].text == val) {
				this.page.gpsAntenna = val;
			}
		}
	}
	//车辆归属change回调
	carAttributionChange(val) {
		this.page.carAttribution = val;
		if (val == 2) {
			this.page.motorcadeName = '';
			this.page.motorcadeContact = '';
			this.page.motorcadeContactPhone = '';
		}
	}
	//全局请求 天线配置接口 GPS天线/GSM天线
	getGpsInfo() {
		this.jsonApiService.http("gpsAntenna/getGpsInfo.html", '').subscribe(data => {
			if (data.success) {
				var obj;
				allSelectOptionsObj.gpsOptions = [];
				allSelectOptionsObj.gsmOptions = [];
				for (var i = 0; i < data.data.length; i++) {
					if (data.data[i].type == 'GPS天线') {
						obj = {
							value: data.data[i].antennaName,
							text: data.data[i].antennaName
						}
						allSelectOptionsObj.gpsOptions.push(obj);

					} else if (data.data[i].type == 'GSM天线') {
						obj = {
							value: data.data[i].antennaName,
							text: data.data[i].antennaName
						}
						allSelectOptionsObj.gsmOptions.push(obj);
					}
				}
				this.gpsOptions = allSelectOptionsObj.gpsOptions;
				this.gsmOptions = allSelectOptionsObj.gsmOptions;
			}
		})
	}
	//图片上传
	// fileChange(files: FileList){
	// 	this.fileData = files.item(0);
	// 	const isJPG = this.fileData.type === 'image/jpeg'|| this.fileData.type === 'image/jpg'|| this.fileData.type === 'image/png';
	//     if (!isJPG) {
	//       	this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
	//       	return;
	//     }
	// 	var reader = new FileReader();
	//     reader.readAsDataURL(this.fileData);
	//     var that = this;
	//     reader.onload = function(e) {  // 图片base64化
	//         var newUrl = this.result;
	//         that.fileImg = newUrl;
	//         if(that.fileImg){
	//         	that.imgFileTitle = '点击更换';
	//         }else{
	//         	that.imgFileTitle = '点击上传';
	//         }
	//     };
	// }

	// 验证项目已存在相同车牌号码
	verifyAlikeCar() {
		let params = {
			id: this.carId,
			companyId: this.page.companyId,
			carNumber: this.page.carNumber
		}
		this.jsonApiService.http_obj('car/checkCarNumberByCompany.html', params).subscribe(data => {
			if (!data.success && data.message) {
				this.jsonApiService.confirm_message(data.message).then(() => {
					this.updata();
				})
				document.getElementById('saveBtn').removeAttribute('disabled')
			} else {
				this.updata();
			}
		})
	}

	//表单提交
	onSubmit(e) {
		if (this.pageType === 'updata') {
			this.timer = setTimeout(() => {
				$('#upCarForm').bootstrapValidator('validate'); //开启验证
				let isValid = $('#upCarForm').data('bootstrapValidator').isValid();  //验证是否通过
				if (isValid) {
					// 验证项目已存在相同车牌号码 再提交表单
					this.verifyAlikeCar()
				}
			}, 200)
		}
	}
	//表单提交
	updata() {
		this.page.inputDate = $('#inputDate').val();
		var Url = '';
		clearTimeout(this.timer);
		var reqdata = new FormData();
		this.page.useTypeL2 = $('#useTypeSelect').val();
		this.page.useTypeL1 = $('#useTypeSelect').val().slice(0, 2);
		if (this.page.sensorChannel) {
			for (let iems of this.page.sensorChannel) {
				if (!iems) iems = '';
			}
		} else {
			this.page.sensorChannel = [];
		}
		if (this.page.sensorAxle == null || this.page.sensorAxle.length == 0) {
			if (this.sensorAxleAfter.length != 0) {
				let sensorAxleList = [];
				for (let j = 0; j < this.sensorAxleAfter.length; j++) {
					sensorAxleList.push(0)
				}
				this.page.sensorAxle = this.deepClone(sensorAxleList);
			}
		}
		for (let item in this.page) {
			if (item == 'sensorPosition') {
				this.page.sensorPosition = this.filterPosition(this.installArray);
				reqdata.append('sensorPositionJson', JSON.stringify(this.page.sensorPosition));
			} else if (item == 'imageInfo') {
				// 暂不限制必须上传
				// let wholeTrue = true;
				// let curEle: any = {};
				// for(let i = 0; i < this.imageInfo.length; i++){
				// 	console.log(this.imageInfo[i])
				// 	if(this.imageInfo[i].imageList.length == 0){
				// 		curEle = this.imageInfo[i];
				// 		wholeTrue = false;
				// 		break;
				// 	}
				// }
				// if(!wholeTrue) {
				// 	this.jsonApiService.message(`请上传${curEle.text}照片`);
				// 	$("#upCarForm").data('bootstrapValidator').resetForm();
				// 	return;
				// }
				this.page.imageInfo = this.filter(this.imageInfo);
				reqdata.append('imageInfoJson', JSON.stringify(this.page.imageInfo));
			} else {
				reqdata.append(item, common.stringTrim(this.page[item]));
			}
		}
		// reqdata.append('type', '2');
		// reqdata.append('file',this.fileData);
		if (this.pageType === 'new') {
			Url = 'car/add.html';
		} else if (this.pageType === 'updata') {
			Url = 'car/edit.html';
		}
		this.jsonApiService.form_http(Url, reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.router.navigate(['/system/car'], { queryParams: { nowPage: this.curPage } });
			}
		})
	}
	//返回资源列表页
	goBack() {
		this.router.navigate(['/system/car'], { queryParams: { nowPage: this.curPage } });
	}
	//公司树选中
	companySelected(data) {
		this.page.companyId = data.companyId || '';
		document.getElementById('saveBtn').removeAttribute('disabled')
	}
	ngOnDestroy() { }
	//设备详细
	getDeviceDetail() {
		let reqdata = 'id=' + this.carId;
		this.jsonApiService.http("car/carInfo.html", reqdata).subscribe(data => {
			if (data.success) {
				for (let item in this.page) {
					if (item === 'carType') {
						this.page[item] = data.data[item] === '请选择' ? '' : data.data[item];
					} else {
						if (item == 'sensorChannel' && !data.data[item]) {
							data.data[item] = [];
						}
						this.page[item] = data.data[item];
						if (item == 'isShared') {
							this.page[item] = data.data[item] ? data.data[item] + '' : '0';
						}
						if (item == 'type') {
							this.page[item] = data.data[item] ? data.data[item] + '' : '1';
						}
						if (item == 'carAttribution') {
							this.page[item] = data.data[item] === null ? '' : data.data[item];
						}
						if (item == 'userIdForCreate' && this.userList) {
							$('#userNameForCreate').val(data.data[item]).change()
							$('#userSelect2').val(data.data[item]).trigger('change')
						}
					}
				}
				let resultChannel = [];
				if (data.data.sensorChannel) {
					for (let item of data.data.sensorChannel) {
						if (item && item !== 'null') {
							resultChannel.push(item);
						}
					}
					data.data.sensorChannel = resultChannel;
				}
				if (data.data.icoPath) {
					this.fileImg = config.BaseURL + data.data.icoPath.substring(1, data.data.icoPath.length);
				}
				if (data.data.sensorChannel.length > 0) {
					for (var i = 0; i < data.data.sensorChannel.length; i++) {
						this.sensorArr[data.data.sensorChannel[i] - 1].checked = true;
					}
				}
				this.selectedCompanyId = data.data.companyId;
				this.selectedCompanyName = data.data.parentName;
				$('#useTypeSelect').val(this.page.useTypeL2).trigger('change');

				this.completionImg(data.data.imageInfo)
				this.ChannelLen = data.data.carAxleAmount;
				//选中通道值
				this.showLocation(data.data.sensorChannel, data.data.sensorPosition, data.data.carAxleAmount)

				let sensor1, sensor2;
				var AxleFrontList = JSON.parse(JSON.stringify(this.sensorAxleFront))
				var AxleAfterList = JSON.parse(JSON.stringify(this.sensorAxleAfter))
				// this.sensorAxleAfter = this.deepClone(this.sensorAxleFront); //深拷贝
				for (let j = 0; j < data.data.sensorChannel.length; j++) {
					if (data.data.sensorAxle == null || data.data.sensorAxle.length == 0) {
						sensor1 = {
							mark: data.data.sensorChannel[j],
							text: data.data.sensorChannel[j],
							checked: false,
							isDisable: false
						}

						AxleFrontList.push(sensor1);
						AxleAfterList.push(sensor1)
					} else {
						for (let k = 0; k < data.data.sensorAxle.length; k++) {
							if (data.data.sensorAxle[k] == 0 && k == j) {
								sensor1 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: false,
									isDisable: false
								}
								AxleFrontList.push(sensor1);
								AxleAfterList.push(sensor1);

							} else if (data.data.sensorAxle[k] == 1 && k == j) {
								sensor1 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: true,
									isDisable: false
								}
								sensor2 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: false,
									isDisable: true
								}
								AxleFrontList.push(sensor1);
								AxleAfterList.push(sensor2);
							} else if (data.data.sensorAxle[k] == 2 && k == j) {
								sensor1 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: false,
									isDisable: true
								}
								sensor2 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: true,
									isDisable: false
								}
								AxleFrontList.push(sensor1);
								AxleAfterList.push(sensor2);
							}
						}
					}
					this.sensorAxleFront = this.deepClone(AxleFrontList); //深拷贝
					this.sensorAxleAfter = this.deepClone(AxleAfterList); //深拷贝
				}
			} else {
				this.jsonApiService.message(data.message);
			}

		})
	}
	//显示安装位置
	showLocation(sensorChannel, value, Lens) {
		var installArray = [
			{
				"index": 1,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 2,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 3,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 4,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 5,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 6,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
		] //安装位置
		let sensor;
		let array = [];
		this.checkChannel = [];
		if (sensorChannel != 0) {
			for (let i = 0; i < sensorChannel.length; i++) {
				sensor = {
					mark: sensorChannel[i],
					text: sensorChannel[i],
					checked: false,
					isDisable: false
				}
				this.checkChannel.push(sensor);
				this.checkChannel.sort(this.compare('mark'));
				var checkChannelList = JSON.parse(JSON.stringify(this.checkChannel));
			}
		}
		var len
		if (value != null && value.length != 0) {
			len = value[value.length - 1].index
		} else {
			if (Lens == "") { Lens = 0 }
			len = Lens;
		};
		if (value != 0 && value != null) {
			for (let j = 0; j < installArray.length; j++) {
				for (let k = 0; k < value.length; k++) {
					if (installArray[j].index == value[k].index) {
						for (let f = 0; f < value[k].positionLMR.length; f++) {
							if (value[k].positionLMR[f].position == 'L') {
								installArray[j].positionLMR[0].sensorChannel = value[k].positionLMR[f].sensorChannel;
								continue;
							}
							if (value[k].positionLMR[f].position == 'M') {
								installArray[j].positionLMR[1].sensorChannel = value[k].positionLMR[f].sensorChannel;
								continue;
							}
							if (value[k].positionLMR[f].position == 'R') {
								installArray[j].positionLMR[2].sensorChannel = value[k].positionLMR[f].sensorChannel;
								continue;
							}
						}
						break;
					}
				}

			}
			if (len > Lens || len == Lens) {
				if (len != 0) { installArray.splice(len, 6 - len); }
			} else {
				if (len != 0) { installArray.splice(Lens, 6 - Lens); }
			}

			this.installArray = this.deepClone(installArray)
		} else {
			if (len != 0) { installArray.splice(len, 6 - len); }
			this.installArray = this.deepClone(installArray)
		}

		this.showCheck(this.checkChannel);
	}
	//初始化日期插件
	initDate() {
		common.initDatePicker("#inputDate", 0);
	}
	ngOnInit() {
		const that = this
		that.getGpsInfo(); //请求天线配置接口
		if (that.inputParam.length == 0) { that.querySensor(); }// 请求传感器列表接口
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			() => { System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => { that.initDate(); }); }
		);
		System.import('assets/js/viewer/viewer.js').then(
			() => {
				System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
					() => {
						System.import('assets/js/viewer/viewer.css').then(() => {
						})
					})
			})
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				that.initAllOutUser().then(() => {
					that.initUserSelect2()
					if (that.pageType === 'updata') {
						let userName = common.getCookie('userName');
						if (userName == 'admin') {
							that.isAdmin = true;
						} else {
							that.isAdmin = false;
						}
						that.getDeviceDetail();
						that.page_title = '编辑';
					} else {
						that.page_title = '新增';
						return
					}
				})
			})
		})
		
	}
	//请求传感器类型的接口
	querySensor() {
		this.jsonApiService.http('sensorManage/querySensorList.html', '').subscribe(data => {
			if (data.success) {
				this.inputParam = data.data
			}
		})
	}
	inputParam: any = [];
	//是否多厂区拉货
	isSharedChange(val) {
		this.page.isShared = val;
	}
	deviceTypeChange(val) {
		this.page.type = val
	}
	imageInfo: any = [
		{
			"Indexes": 0,
			"index": 1,
			"text": "车辆正面",
			"imgFileTitle": '点击上传',
			"imageList": [],
			'describe': 'carfront',
			'localImg': [],
		},
		{
			"Indexes": 1,
			"index": 2,
			"text": "车辆侧面",
			"imgFileTitle": '点击上传',
			"imageList": [],
			'describe': 'carside',
			'localImg': [],
		},
		{
			"Indexes": 2,
			"index": 3,
			"text": "主机",
			"imgFileTitle": '点击上传',
			"imageList": [],
			'describe': 'host',
			'localImg': [],
		},
		{
			"Indexes": 3,
			"index": 5,
			"text": "天线",
			"imgFileTitle": '点击上传',
			"imageList": [],
			'describe': 'aerial',
			'localImg': [],
		},
		{
			"Indexes": 4,
			"index": 4,
			"text": "传感器",
			"imgFileTitle": '点击上传',
			"imageList": [],
			'describe': 'sensor',
			'localImg': [],
		},
		{
			"Indexes": 6,
			"index": 7,
			"text": "电源",
			"imgFileTitle": '点击上传',
			"imageList": [],
			'describe': 'power',
			"localImg": []
		},
		{
			"Indexes": 7,
			"index": 8,
			"text": "行驶证",
			"imgFileTitle": '点击上传',
			"imageList": [],
			'describe': 'drivingLicense',
			"localImg": []
		},
		{
			"Indexes": 5,
			"index": 6,
			"text": "其他",
			"imgFileTitle": '点击上传',
			"imageList": [],
			'describe': 'other',
			'localImg': [],
		},
		{
			"Indexes": 8,
			"index": 9,
			"text": "付款凭证",
			"imgFileTitle": '点击上传',
			"imageList": [],
			'describe': 'voucher',
			'localImg': [],
		}
	] //图片List
	isViewer: boolean = false; //默认隐藏
	//安装图片
	fileListChange(index, files: FileList) {
		if (this.isViewer && $(".viewer-container").length > 0) {
			this.viewer.destroy();
		}
		var that = this;
		that.fileList = files.item(0);
		const isJPG = that.fileList.type === 'image/jpeg' || that.fileList.type === 'image/jpg' || that.fileList.type === 'image/png';
		if (!isJPG) {
			that.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
			return;
		}
		that.imageInfo[index].imageList = [];
		that.imageInfo[index].localImg = [];
		that.uploloadImg(that.imageInfo[index], this.fileList).then((result) => {
			// let localImg;
			// if(result[0][0] == '/'){
			// 	localImg = config.BaseURL + result[0].substr(1);
			// }else{
			// 	localImg = config.BaseURL + result[0];
			// }

			let localImg;
			if (result[0].indexOf('http') == -1) {
				if (result[0][0] == '/') {
					localImg = config.BaseURL + result[0].substr(1);
				} else {
					localImg = config.BaseURL + result[0];
				}
			} else {
				localImg = result[0];
			}
			that.imageInfo[index].imageList.push(result[0]);
			that.imageInfo[index].localImg.push(localImg);
			if (that.imageInfo[index].imageList.length != 0) {
				that.imageInfo[index].imgFileTitle = '点击更换';
			} else {
				that.imageInfo[index].imgFileTitle = '点击上传';
			}
		})
		for (let k = 0; k < $(".up").length; k++) {
			$(".up")[k].value = null;
		}
	}
	//上传多张
	multifileChange(index, files: FileList) {
		if (this.isViewer && $(".viewer-container").length > 0) {
			this.viewer.destroy();
		}

		var that = this;
		let multfileList = files;
		// let multfileListLen = files.length + that.imageInfo[index].imageList.length;
		// if (multfileListLen > 4 && index == 4) {
		// 	this.jsonApiService.message('传感器最多只能上传4张图片');
		// 	return;
		// }

		var reqdata = new FormData();
		reqdata.append('describe', that.imageInfo[index].describe);
		reqdata.append('businessType', '1');
		reqdata.append('deviceId', this.page.deviceId);
		reqdata.append('type', '2'); //type 1获取相对路径  2获取绝对路径

		for (var i = 0; i < multfileList.length; i++) {
			this.fileList = multfileList[i];
			const isJPG = this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png';
			if (!isJPG) {
				this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
				return;
			}

			reqdata.append('files', multfileList[i]);

		}


		that.jsonApiService.form_http("fileUpload/upload.html", reqdata).subscribe(data => {
			// that.jsonApiService.message(data.message);
			if (data.success) {
				for (var i = 0; i < data.data.length; i++) {
					that.imageInfo[index].imageList.push(data.data[i]);
					let localImg;
					// if(data.data[i][0] == '/'){
					// 	localImg = config.BaseURL + data.data[i].substr(1);
					// }else{
					// 	localImg = config.BaseURL + data.data[i];
					// }
					if (data.data[i].indexOf('http') == -1) {
						if (data.data[i][0] == '/') {
							localImg = config.BaseURL + data.data[i].substr(1);
						} else {
							localImg = config.BaseURL + data.data[i];
						}
					} else {
						localImg = data.data[i];
					}
					that.imageInfo[index].localImg.push(localImg);
				}
			}
		})


		for (let k = 0; k < $(".up").length; k++) {
			$(".up")[k].value = null;
		}

	}
	//删除
	deleteImg(index, i) {
		this.imageInfo[index - 1].imageList.splice(i, 1);
		this.imageInfo[index - 1].localImg.splice(i, 1);

		if (this.isViewer && $(".viewer-container").length > 0) {
			this.viewer.destroy();
		}
	}
	bigImg: any = '' //
	bigImgClick(modal, img) {
		// modal.show();
		this.bigImg = img;
		if (this.isViewer && $(".viewer-container").length > 0) {
			System.import('assets/js/viewer/viewer.js').then(
				() => {
					System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
						() => {
							System.import('assets/js/viewer/viewer.css').then(() => {
								this.showImg();
							})
						})
				})
		} else {
			this.showImg();
		}


	}
	//显示图片组件
	viewer: any = '';
	showImg() {
		var that = this;
		var imgList = $(".imgFileList")[0];
		this.viewer = new Viewer(imgList, {
			url: 'src',
			title: function (image) {
				return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
			},
		});
		that.isViewer = true
	}
	CloseBigImg(modal) {
		modal.hide();
	}
	//图片上传
	uploloadImg(list, files) {
		var that = this;
		var List = [];
		var reqdata = new FormData();
		reqdata.append('describe', list.describe);
		reqdata.append('businessType', '1');
		reqdata.append('deviceId', this.page.deviceId);
		reqdata.append('type', '2'); //type 1获取相对路径  2获取绝对路径
		reqdata.append('files', files);
		return new Promise(function (resolve, reject) {
			that.jsonApiService.form_http("fileUpload/upload.html", reqdata).subscribe(data => {
				// that.jsonApiService.message(data.message);
				if (data.success) {
					List = data.data
					resolve(List);
				}
			})
		})
	}
	//过滤图片数组值
	filter(value) {
		var imgList = []
		for (let i = 0; i < value.length; i++) {
			if (value[i].imageList.length != 0) {
				var img = {
					"index": value[i].index,
					"imageList": value[i].imageList,
				}
				imgList.push(img);
			}
		}

		return imgList
	}
	//过滤通道数据
	filterPosition(value) {
		var List = [];
		var ListParant = [];
		this.page.sensorPosition = [];
		for (let j = 0; j < value.length; j++) {
			if (value[j].positionLMR[0].sensorChannel.length != 0
				&& value[j].positionLMR[1].sensorChannel.length != 0
				&& value[j].positionLMR[2].sensorChannel.length != 0) {
				List.push(value[j])
			} else {

				for (let a = 0; a < value[j].positionLMR.length; a++) {

					if (value[j].positionLMR[a].sensorChannel.length != 0) {
						ListParant.push(value[j].positionLMR[a]);
					}
				}
				if (ListParant.length != 0) {
					var positionLMR = {
						"index": j + 1,
						"positionLMR": ListParant
					}
					List.push(positionLMR);
				}

				// if(ListParant.length != 0){List.push(ListParant);}
				ListParant = [];
				continue;
			}
		}
		return List;
	}
	//补全图片
	completionImg(value) {
		if (value == null) {
			return;
		}
		if (value.length == 0) {
			return;
		}
		for (var a = 0; a < this.imageInfo.length; a++) {
			for (var b = 0; b < value.length; b++) {
				if (this.imageInfo[a].index == value[b].index) {
					this.imageInfo[a].imageList = value[b].imageList;
					for (let c = 0; c < value[b].imageList.length; c++) {
						let localImg;
						// if(value[b].imageList[c][0] == '/'){
						// 	localImg = config.BaseURL + value[b].imageList[c].substr(1);
						// }else{
						// 	localImg = config.BaseURL + value[b].imageList[c];
						// }
						if (value[b].imageList[c].indexOf('http') == -1) {
							if (value[b].imageList[c][0] == '/') {
								localImg = config.BaseURL + value[b].imageList[c].substr(1);
							} else {
								localImg = config.BaseURL + value[b].imageList[c];
							}
						} else {
							localImg = value[b].imageList[c];
						}
						// let baseImg = config.BaseURL + value[b].imageList[c]
						this.imageInfo[a].localImg.push(localImg);
					}

					break;
				}
			}
		}
	}

	/**
	 * 责任人
	 */
	userList: any = [] // 责任人员
	// 责任人列表数据
  initAllOutUser() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('user/getUserList.html', null).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            var obj = {
              id: userList[i].id,
              text: userList[i].name + (userList[i].phone ? '-' + userList[i].phone : ''),
              name: userList[i].name,
              userName: userList[i].userName,
              phone: userList[i].phone
            }
            selectdata[i] = obj
          }
        }
        that.userList = selectdata
        resolve()
      })
    })
  }
	// 责任人配置
  initUserSelect2() {
    let that = this
    // 责任人-form参数
    $('#userSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.userList
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        $('#userNameForCreate').val(data.text).change()
        that.page.userNameForCreate = data.name
        that.page.userIdForCreate = data.id
      })
	}
	// 删除责任人
  delUserName() {
    this.page.userNameForCreate = ''
    this.page.userIdForCreate = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#userSelect2').val('')
    $('#select2-userSelect2-container').empty()
    $('#select2-userSelect2-container').attr('title', '')
    $('#select2-userSelect2-container').prepend(str)
  }
}